package com.dhcc.bpm.business.papc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.business.papc.entity.BatchRecord;
import com.dhcc.bpm.business.papc.entity.BatchSchedule;
import com.dhcc.bpm.business.papc.service.IBatchRecordService;
import com.dhcc.bpm.business.papc.service.IBatchScheduleService;
import com.dhcc.bpm.business.papc.vo.BatchScheduleVO;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.modules.system.service.ISerialNumberService;
import com.dhcc.bpm.modules.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 批量任务计划表  控制器
 *
 * @author zhanghang
 * @since 2020-12-18
 */
@RestController
@AllArgsConstructor
@RequestMapping("bpm-papc/batchschedule")
@Api(value = "批量任务计划表 ", tags = "批量任务计划表 接口")
public class BatchScheduleController extends BladeController {

	private IUserService            userService;
	private IBatchRecordService     batchRecordService;
	private IBatchScheduleService   batchScheduleService;
	private ISerialNumberService serialNumberService;
	@Autowired
	private DiscoveryClient discoveryClient;
	private static final Logger LOGGER = LoggerFactory.getLogger(BatchScheduleController.class);

	/**
	 * 批量任务计划 启用或者停用
	 */
	@GetMapping("/startOrStop")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "启用或者停用", notes = "停用/启用")
	@Transactional
	public R<Boolean> startOrStop(@ApiParam(value = "主键集合", required = true) @RequestParam String ids,
								  @ApiParam(value = "任务开关 0 开启 1 关闭", required = true) @RequestParam String taskOpen) {

		List<BatchRecord>   batchRecordUpdateList   = new ArrayList<>();
		List<BatchSchedule> batchScheduleUpdateList = new ArrayList<>();

		List<BatchSchedule> batchSchedulePojoList = new ArrayList<>();
		try {
			List<Long> idList = Func.toLongList(ids);
			for (Long id : idList) {
				BatchSchedule batchSchedulePojo = batchScheduleService.getById(id);
				// 添加当前任务
				batchSchedulePojoList.add(batchSchedulePojo);
				if (null == batchSchedulePojo.getPid()) {
					// 如果是父任务，则还需修改其子任务
					QueryWrapper<BatchSchedule> queryWrapper = new QueryWrapper<>();
					queryWrapper.eq("PID", batchSchedulePojo.getId());
					batchSchedulePojoList.addAll(batchScheduleService.list(queryWrapper));
				}
			}

			for (BatchSchedule batchSchedulePojo : batchSchedulePojoList) {

				BatchSchedule batchSchedule = new BatchSchedule();
				batchSchedule.setId(batchSchedulePojo.getId());
				batchSchedule.setTaskOpen(taskOpen);
				batchScheduleUpdateList.add(batchSchedule);

				/**
				 * 查询记录表里 是否有该批量任务计划
				 * 如果有则也要修改停用启用状态
				 * 如果没有则忽略
				 */
				BatchRecord batchRecordQuery = new BatchRecord();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String zjywSysDate = sdf.format(new Date());
				batchRecordQuery.setZjywSysDate(zjywSysDate);
				batchRecordQuery.setPkTaskNo(batchSchedulePojo.getPkTaskNo());
				batchRecordQuery.setOrderNo( batchSchedulePojo.getOrderNo());
				batchRecordQuery.setPrdtCode(batchSchedulePojo.getPrdtCode());
				batchRecordQuery.setPkType(  batchSchedulePojo.getPkType());
				List<BatchRecord> batchRecordPojoList = batchRecordService.selectZjywBatchRecordList(batchRecordQuery);
				for (BatchRecord batchRecordPojo : batchRecordPojoList) {
					BatchRecord batchRecord = new BatchRecord();
					batchRecord.setId(batchRecordPojo.getId());
					batchRecord.setTaskOpen(taskOpen);
					batchRecordUpdateList.add(batchRecord);
				}
			}

			if (!batchRecordUpdateList.isEmpty()) {
				batchRecordService.updateBatchById(batchRecordUpdateList);
			}
			if (!batchScheduleUpdateList.isEmpty()) {
				batchScheduleService.updateBatchById(batchScheduleUpdateList);
			}

			if ("0".equals(taskOpen)) {
				return R.success("启用成功！");
			} else {
				return R.success("停用成功！");
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			//手动强制回滚事务，这里一定要第一时间处理
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.fail(e.getMessage());
		}
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入batchSchedule")
	public R<BatchSchedule> detail(BatchSchedule batchSchedule) {
		BatchSchedule detail = batchScheduleService.getOne(Condition.getQueryWrapper(batchSchedule));
		return R.data(detail);
	}

	/**
	 * 分页 批量任务计划表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入batchSchedule")
	public R<IPage<BatchSchedule>> list(BatchSchedule batchSchedule, Query query) {
		IPage<BatchSchedule> pages = batchScheduleService.page(Condition.getPage(query), Condition.getQueryWrapper(batchSchedule));
		return R.data(pages);
	}

	/**
	 * 自定义分页 批量任务计划表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入batchSchedule")
	public R<IPage<BatchScheduleVO>> page(BatchScheduleVO batchSchedule, Query query) {
		if (batchSchedule.getPid()!=null){
			IPage<BatchScheduleVO> pages = batchScheduleService.selectBatchSchedulePage(Condition.getPage(query), batchSchedule);
			List<BatchScheduleVO> list = pages.getRecords();
			for (BatchScheduleVO vo : list) {
				if (null != vo.getIpAddr()) {
					String a = vo.getIpAddr().substring(7).split("/")[0];
					String status2 = socketStatusByName(a);
					vo.setServerStatus(status2);
				}
				//查用户名
//			User user = userService.getById(vo.getCreateUser());
//			if(user != null){
//				vo.setCreateUserName(user.getRealName());
//			}
			}
			pages.setRecords(list);
			return R.data(pages);
		}else {
			IPage<BatchScheduleVO> pages = batchScheduleService.selectBatchSchedulePage(Condition.getPage(query), batchSchedule);
			List<BatchScheduleVO> list = pages.getRecords();
			BatchSchedule bat = new BatchSchedule();
			for (BatchScheduleVO vo : list) {
				bat.setPid(vo.getId());
//				IPage<BatchScheduleVO> pages1 = batchScheduleService.selectBatchSchedulePage(Condition.getPage(query), bat);
				List<BatchSchedule> list1 = batchScheduleService.list(Condition.getQueryWrapper(bat));
//				List<BatchScheduleVO> list1 = pages1.getRecords();
				for (BatchSchedule vo1 : list1) {
					if (null != vo1.getIpAddr()) {
						String a = vo1.getIpAddr().substring(7).split("/")[0];
						String status2 = socketStatusByName(a);
						if (status2=="异常") {
							vo.setServerStatus("异常");
						}
					}
					if(vo.getServerStatus()==null){
						vo.setServerStatus("健康");
					}
				}

			}
			pages.setRecords(list);
			return R.data(pages);
		}


	}

	/**
	 * 新增 批量任务计划表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入batchSchedule")
	public R<Boolean> save(@Valid @RequestBody BatchSchedule batchSchedule) {
		return R.status(batchScheduleService.save(batchSchedule));
	}

	/**
	 * 修改 批量任务计划表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入batchSchedule")
	public R<Boolean> update(@Valid @RequestBody BatchSchedule batchSchedule) {
		return R.status(batchScheduleService.updateById(batchSchedule));
	}

	/**
	 * 新增或修改 批量任务计划表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入batchSchedule")
	@Transactional
	public R<Boolean> submit(@Valid @RequestBody BatchSchedule batchSchedule) {
		// 1.初始化待批量更新集合
		List<BatchRecord>   batchRecordUpdateList   = new ArrayList<>();
		List<BatchSchedule> batchScheduleUpdateList = new ArrayList<>();

		List<BatchSchedule> batchSchedulePojoList = new ArrayList<>();
		try {
			if (null != batchSchedule.getId()) {
				// id不为空 则是修改
				BatchSchedule batchSchedulePojo = batchScheduleService.getById(batchSchedule.getId());
				batchSchedulePojoList.add(batchSchedulePojo);
				// pid为null表示有子任务
				if (null == batchSchedulePojo.getPid()) {
					QueryWrapper<BatchSchedule> wrapper = new QueryWrapper<>();
					wrapper.eq("PID", batchSchedule.getId());
					List<BatchSchedule> batchScheduleList = batchScheduleService.list(wrapper);
					if (!batchScheduleList.isEmpty()) {
						// 如果list不为空，表示有子任务
						batchSchedulePojoList.addAll(batchScheduleList);
					}
				}

				for (BatchSchedule schedulePojo : batchSchedulePojoList) {
					BatchSchedule scheduleUpdatePojo = new BatchSchedule();
					BeanUtils.copyProperties(batchSchedule, scheduleUpdatePojo);
					scheduleUpdatePojo.setId(schedulePojo.getId());
					batchScheduleUpdateList.add(scheduleUpdatePojo);

					/**
					 * 查询记录表里 是否有该批量任务计划
					 * 如果有则也要修改停用启用状态
					 * 如果没有则忽略
					 */
					BatchRecord batchRecordQuery = new BatchRecord();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
					String zjywSysDate = sdf.format(new Date());
					batchRecordQuery.setZjywSysDate(zjywSysDate);
					batchRecordQuery.setPkTaskNo(schedulePojo.getPkTaskNo());
					batchRecordQuery.setOrderNo( schedulePojo.getOrderNo());
					batchRecordQuery.setPrdtCode(schedulePojo.getPrdtCode());
					batchRecordQuery.setPkType(  schedulePojo.getPkType());
					List<BatchRecord> batchRecordPojoList = batchRecordService.selectZjywBatchRecordList(batchRecordQuery);
					for (BatchRecord batchRecordPojo : batchRecordPojoList) {
						BatchRecord batchRecord = new BatchRecord();
						BeanUtils.copyProperties(batchSchedule, batchRecord);
						batchRecord.setId(batchRecordPojo.getId());
						batchRecordUpdateList.add(batchRecord);
					}
				}

				if (!batchRecordUpdateList.isEmpty()) {
					batchRecordService.updateBatchById(batchRecordUpdateList);
				}
				if (!batchScheduleUpdateList.isEmpty()) {
					batchScheduleService.updateBatchById(batchScheduleUpdateList);
				}
			} else {
				batchScheduleService.saveOrUpdate(batchSchedule);
			}
			return R.success("修改成功！");
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			//手动强制回滚事务，这里一定要第一时间处理
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.fail(e.getMessage());
		}
	}


	/**
	 * 删除 批量任务计划表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R<Boolean> remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
//		return R.status(batchScheduleService.removeByIds(Func.toLongList(ids)));
		return R.status(batchScheduleService.delIdAndPid(Func.toLongList(ids)));
	}
	public String socketStatusByName(String hostname) {
		//获取服务名称  //获取服务中的实例列表
		List<String> serviceNames = discoveryClient.getServices();
		Optional<String> optional = serviceNames.stream().filter(item -> hostname.equalsIgnoreCase(item)).findAny();
//            InetAddress address = InetAddress.getByName(hostname);
//            boolean flag = address.isReachable(3000);
		boolean isEixit = optional.isPresent();
		if (!isEixit) {
			return "异常";
		}
		return "健康";

	}

	/**
	 * @return org.springblade.core.tool.api.R
	 * @Description 自动生成编码
	 * @Author 王静晗
	 * @Date 2022年5月6日15:53:41
	 **/
	@PostMapping("/autoCreateCode")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "自动生成批量产品编号", notes = "")
	@ApiLog("自动生成编号")
	@Log(title = "自动生成编号", businessType = BusinessType.OTHER)
	public R autoCreateCode() {
		try {
			String appId = serialNumberService.generateSerialNumberByModelCode("pk_task_no");
			return R.data(appId);
		} catch (Exception e) {
			LOGGER.error("自动生成编号失败:{}", e);
			return R.status(false);
		}
	}

}
